package com.mango.ch02;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

public class CompositeKey implements WritableComparable<CompositeKey> {
    @Override
    public String toString() {
        return "CompositeKey [stockSymbol=" + stockSymbol + ", timestamp=" + timestamp + "]";
    }

    // 自然键 股票码 组合键是一个（stockSymbol，timestamp）
    private Text stockSymbol = new Text();// 股票代码
    private LongWritable timestamp = new LongWritable();

    /**
     * 必须有默认的构造器皿，这样Mapreduce方法才能创建对象，然后通过readFields方法从序列化的数据流中读出进行赋值
     */

    public CompositeKey() {
    }

    public CompositeKey(Text stockSymbol, LongWritable timestamp) {
        this.stockSymbol = stockSymbol;
        this.timestamp = timestamp;
    }

    public Text getStockSymbol() {
        return stockSymbol;
    }

    public void setStockSymbol(Text stockSymbol) {
        this.stockSymbol = stockSymbol;
    }

    public LongWritable getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(LongWritable timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public int compareTo(CompositeKey arg0) {
        // TODO Auto-generated method stub
        //设置键的排序
        if (this.stockSymbol.compareTo(arg0.stockSymbol) != 0) {
            return this.stockSymbol.compareTo(arg0.stockSymbol);
        } else if (this.timestamp.get() != arg0.timestamp.get()) {
            return this.timestamp.get() < arg0.getTimestamp().get() ? -1 : 1;
        } else
            return 0;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        // TODO Auto-generated method stub
        stockSymbol.write(out);
        timestamp.write(out);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        // TODO Auto-generated method stub
        // 按照数据类型来读取值
        stockSymbol.readFields(in);
        timestamp.readFields(in);
    }

}
